package com.example.demoappsocketserver;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.example.demoappsocketserver.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private static String SOCKET_SERVER = "socket_server";
    private ActivityMainBinding mBinding;
    /**
     * 启动服务端端口
     * 服务端IP为手机IP
     */
//    private SocketServerOld server = new SocketServerOld(6666);

//    private SocketServerOld2 mSocketServerOld2;
    private SocketServer mSocketServer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
//        mSocketServerOld2 = SocketServerOld2.getInstance();
//        mSocketServerOld2.initListen(8888);
//        mSocketServerOld2.setOnConnectListener(new SocketServerOld2.ConnectListener() {
//            @Override
//            public void onCreateListenerFail(String error) {
//                Log.e(SOCKET_SERVER, "CreateListenerFail: " + error);
//            }
//
//            @Override
//            public void onReceiveData(String data) {
//                Log.d(SOCKET_SERVER, "ReceiveData: " + data);
//                mBinding.tvTxt.setText(data);
//            }
//
//            @Override
//            public void onBrokenPipe(String message) {
//                Log.d(SOCKET_SERVER, "BrokenPipe: " + message);
//            }
//        });
//
//        mBinding.btnSend.setOnClickListener(v -> {
//            mSocketServerOld2.sendData(mBinding.etMsg.getText().toString());
//        });
        mSocketServer = new SocketServer();
        mSocketServer.startServer();
        mSocketServer.setOnServerListener(new SocketServer.OnServerListener() {
            @Override
            public void onServerState(boolean isStarted) {

            }

            @Override
            public void onClientConnectState(String clientIp, int clientPort, int state, String msg) {

            }

            @Override
            public void onReceiveData(String fromClientIp, int fromClientPort, String data) {
                mBinding.tvTxt.setText(fromClientIp + " " + fromClientPort + " " + data);
            }
        });

        mBinding.btnSend.setOnClickListener(v -> {
            mSocketServer.sendData(mBinding.etMsg.getText().toString());
        });
    }


}